package jesss.commands;

import com.amazonaws.AmazonClientException;
import jesss.options.ExtendedGnuParser;
import jesss.options.JesssOptions;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.MissingArgumentException;
import org.apache.commons.cli.Options;

/**
 * User: Lee
 * Date: 8/21/13
 * Time: 11:13 PM
 */
public class DeleteBucketCommand<T> extends AbstractJesssCommand {
    private JesssOptions jesssOptions = null;
    private Options options = new Options();
    private String bucketName = null;

    public DeleteBucketCommand(JesssOptions jesssOptions) throws Exception {
        this.jesssOptions = jesssOptions;
        setOptions();
        try {
            parseArgs(jesssOptions.getArgs());
        } catch (Exception e) {
            printUsage();
            throw e;
        }
    }

    @Override
    public CommandResult<Object> executeCommand() {
        CommandResult<Object> commandResult = new CommandResult<>();

        try {
            jesssOptions.getAmazonS3().deleteBucket(bucketName);
            commandResult.setResultStatus(ResultStatus.Success);
        } catch (AmazonClientException e) {
            commandResult.setResultStatus(ResultStatus.Error);
            commandResult.setStatusMessage(String.format("Unable to delete bucket \"%s\".", bucketName));
            addExceptionInfoToCommandResult(commandResult, e);
        }

        return commandResult;
    }

    private void printUsage() {
        System.out.println("Usage:");
        System.out.println("jesss.jesss -cn db -bn <mybucket>");

    }

    private void setOptions() {
        options = new Options();
        options.addOption("bn", "bucketName", true, "Bucket name to delete");
    }

    private void parseArgs(String[] args) throws Exception {

        if (args == null || args.length == 0) {
            printUsage();
        }

        try {
            CommandLineParser parser = new ExtendedGnuParser(true);
            CommandLine cmd = parser.parse(options, args);

            if (cmd.hasOption("bn")) {
                bucketName = cmd.getOptionValue("bn");
            } else {
                throw new MissingArgumentException("Missing bucket name parameter.");
            }
        } catch (Exception e) {
            printUsage();
            throw e;
        }
    }
}
